package Catalyst::View::SXML;
use warnings;
use strict;

use Guile::Space;

sub render {
    my ( $self, $c, $template, $args ) = @_;
    my $space = Guile::Space->new;
    $args->{ _template_file } = $template;
    return $space->run( code => '(render-template-file _template_file)', scope => $args );
}

sub _load_template {
    my ( $self, $template ) = @_;
    open my $fh, '<', $template or die "Unable to open '$template': $!\n";
    local $/;
    return <$fh>;
}

use Inline Guile => q(

    (set! %load-path 
          (list "/usr/share/guile/site"
                "/usr/share/guile/1.6"))
    
    (use-modules (sxml simple)
                 (sxml transform)
                 (sxml xpath)
                 (texinfo reflection)
                 (texinfo html)
                 (srfi srfi-13))

    (define content #f)         ; wrapped content global

    (define wrapper
      (lambda (fn . c)
        (let ((tree #f)
              (result #f))
             (set!   tree     (read (open-input-file fn)))
             (set!   content  (apply (lambda ls (begin ls)) c))
             (include-template fn) )))

    (define render-template
      (lambda (raw-template)
        (with-output-to-string (lambda () 
                                 (sxml->xml raw-template)))))

    (define render-template-file
      (lambda (_template_file)
        (with-output-to-string (lambda ()
                                 (sxml->xml (include-template
                                 _template_file))))))

    (define include-template
      (lambda (fn)
        (let ((tree #f))
             (set! tree (read (open-input-file fn)))
             (primitive-eval tree))))

);

1;
